package day52.pet.service.impl;

import day52.basic.commonenum.ErrorCode;
import day52.basic.domain.Point;
import day52.basic.domain.dto.AcceptOrderDto;
import day52.basic.exception.CustomException;
import day52.basic.util.*;
import day52.org.domain.Shop;
import day52.org.mapper.ShopMapper;
import day52.pet.domain.OrderPetAcquisition;
import day52.pet.domain.Pet;
import day52.pet.domain.SearchMasterMsg;
import day52.pet.domain.SearchMasterMsgAuditLog;
import day52.pet.mapper.OrderPetAcquisitionMapper;
import day52.pet.mapper.PetMapper;
import day52.pet.mapper.SearchMasterMsgAuditLogMapper;
import day52.pet.mapper.SearchMasterMsgMapper;
import day52.pet.service.ISearchMasterMsgService;
import day52.basic.service.impl.BaseServiceImpl;
import day52.user.domain.Logininfo;
import day52.user.domain.User;
import day52.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Yang
 * @since 2022-12-27
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private PetMapper petMapper;

    @Override
    @Transactional
    public AjaxResult publish(SearchMasterMsg msg, HttpServletRequest request) throws Exception {
        //根据请求获取当前登陆用户
        Logininfo lf = CurrentLoginInfoUtil.currentLoginInfo(request);
        if (lf == null){
            throw new CustomException();
        }
        //根据logininfo信息查询当前用户查询user
        User user = userMapper.findByLogininfoId(lf.getId());
        //寻主消息存入数据库
        msg.setUserId(user.getId());
        msg.setState(0);
        searchMasterMsgMapper.add(msg);
        //智能审核
        Boolean result = BaiduAuditUtils.TextCensor(msg.getName() + msg.getTitle() + msg.getCoatColor());
        //审核通过，修改状态审核通过，查询50km内的店铺，分配给寻主消息
        if(result){
            msg.setState(1);
            //保存审核日志信息
            SearchMasterMsgAuditLog smal = new SearchMasterMsgAuditLog();
            smal.setMsgId(msg.getId());
            smal.setState(1);
            smal.setAuditTime(new Date());
            smal.setNote("审核通过！");
            searchMasterMsgAuditLogMapper.add(smal);
            //获取寻主消息地址的经纬度
            Point point = DistanceUtils.getPoint(msg.getAddress());
            //查询出所有的店铺
            List<Shop> shops = shopMapper.findAllAvailableShops();
            //找到最近店铺
            Shop shop = DistanceUtils.getNearestShop(point, shops);
            //计算50km内最近的店铺
            if (shop != null){
                //店铺存在则绑定店铺，不存在则不设置shopId
                msg.setShopId(shop.getId());
            }
            msg.setNote("审核通过！");
            searchMasterMsgMapper.update(msg);
            return AjaxResult.me();
        }else{
            //审核不通过，修改状态驳回，发送短信或邮件提醒用户
            msg.setState(-1);
            //SmsihuyiUtil.sendSms(user.getPhone(),"发布内存存在不合法信息，请修改后重新提交！");
            System.out.println("发布内存存在不合法信息，请修改后重新提交！");
            //保存审核日志信息
            SearchMasterMsgAuditLog smal = new SearchMasterMsgAuditLog();
            smal.setMsgId(msg.getId());
            smal.setState(0);
            smal.setAuditTime(new Date());
            smal.setNote("发布内存存在不合法信息，请修改后重新提交！");
            msg.setNote("审核未通过！");
            searchMasterMsgAuditLogMapper.add(smal);
            searchMasterMsgMapper.update(msg);
            return AjaxResult.me().setSuccess(false);
        }
    }

    /**
     * 拒单
     * @param id
     * @return
     */
    @Override
    @Transactional
    public AjaxResult rejectOrder(Long id) {
        //查询订单是否在进行中
        List<OrderPetAcquisition> orders = orderPetAcquisitionMapper.findByMsgId(id);
        if(orders.size() > 0){
            for (OrderPetAcquisition order : orders) {
                if(order.getState() == 0){
                    throw new CustomException(ErrorCode.ORDER_EXISTS.getCode());
                }
            }
        }
        //通过寻主消息id查询寻主消息
        SearchMasterMsg msg = searchMasterMsgMapper.findOne(id);
        //把寻主消息的shopid置空
        msg.setShopId(null);
        //更新寻主消息
        searchMasterMsgMapper.update(msg);
        return AjaxResult.me();
    }

    /**
     * 接单
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public AjaxResult acceptOrder(AcceptOrderDto dto) {
        //查询订单是否在进行中
        List<OrderPetAcquisition> orders = orderPetAcquisitionMapper.findByMsgId(dto.getMsgId());
        if(orders.size() > 0){
            for (OrderPetAcquisition order : orders) {
                if(order.getState() == 0){
                    throw new CustomException(ErrorCode.ORDER_EXISTS.getCode());
                }
            }
        }
        SearchMasterMsg msg = searchMasterMsgMapper.findOne(dto.getMsgId());
        //生成狗子
        Pet pet = msg2pet(dto, msg);
        petMapper.add(pet);
        //生成收购订单
        OrderPetAcquisition opa = msg2order(dto, msg, pet);
        orderPetAcquisitionMapper.add(opa);
        return AjaxResult.me();
    }

    private OrderPetAcquisition msg2order(AcceptOrderDto dto, SearchMasterMsg msg, Pet pet) {
        OrderPetAcquisition opa = new OrderPetAcquisition();
        opa.setOrderSn(CodeGenerateUtils.generateOrderSn(dto.getMsgId()));
        opa.setDigest(dto.getNote());
        opa.setLastcomfirmtime(new Date(System.currentTimeMillis()+3*24*60*60*1000));
        opa.setState(0);
        opa.setPrice(msg.getPrice());
        opa.setPetId(pet.getId());
        opa.setUserId(msg.getUserId());
        opa.setShopId(msg.getShopId());
        opa.setAddress(msg.getAddress());
        opa.setEmpId(dto.getHandlerId());
        opa.setSearchMasterMsgId(msg.getId());
        return opa;
    }

    /**
     * 通过寻主消息初始化狗子信息
     * @param dto
     */
    private Pet msg2pet(AcceptOrderDto dto,SearchMasterMsg msg) {
        Pet pet = new Pet();
        pet.setName(msg.getName());
        pet.setCostprice(msg.getPrice());
        pet.setState(0);
        pet.setTypeId(msg.getPetType());
        pet.setCreatetime(new Date());
        pet.setShopId(msg.getShopId());
        pet.setSearchMasterMsgId(msg.getId());
        return pet;
    }
}
